<?php
include 'api.php';
include 'connect_pdo.php';
include 'classes.php';
include 'err_handler.php';

//set_error_handler("ErrorHandlerFull");

//get highest updated spell
$pdo = new pdo_query;
$pdo->try_query("select spell_id from spell_item order by datestamp desc limit 0,1",'One');
$maxSpell = $pdo->result;

//display form
$maxVal = max($maxSpellEnd[0],$maxSpell[0]);
$location = '"http://www.allmyrandomstuff.com/wow/getspelldifficulty.php"';
echo "<p><form method='post'>";
echo "<input type='text' value='$maxSpell[0]' name='start'/>";
echo '<input type="text" name="end"/>';
echo '<br/><br/><select name="range">';
echo '<option value="1">Next 1</option>';
echo '<option value="50">Next 50</option>';
echo '<option value="100">Next 100</option>';
echo '<option selected="selected" value="250">Next 250</option>';
echo '<option value="500">Next 500</option>';
echo '<option value="1000">Next 1000</option>';
echo '</select><br/>';
echo '<input type="submit" value="Go!"/>';
echo '<input type="hidden" name="submitted" value="1"/>';
echo '</form></p><p style="font-size:75%">';
echo "<input onClick='location.href=$location' type='button' value='reload'/><br/>";
echo "<br/>Highest updated record is $maxVal<br/><br/>";

 $deleteSpell = "DELETE from spell WHERE spell_id=?";
 $deleteSpellItem = "DELETE from spell_item WHERE spell_id=?";


if ($_POST['submitted']==1)
{
	//determine range to run for
	$i = $_POST['start'];
	$range = $_POST['range'];
	$rangeEnd = $range + $i;

	$j = min($rangeEnd,110146);//the end of the range is either 110146 (highest number used) or the set end, whichever is lower

	echo "Running for $i to $j<br/><br/>";

	//declare regex patterns
	$pattern = "/[^0-9]/";
	$pattern2 = "/item=/";
	$pattern3 = "/itemset=/";

	//begin running
	while ($i<=$j)
	{
		//first we check to see if the recipe is still valid
		try{
			$data = $api->getRecipeApi()->getRecipe($i);
			$spellName = $data['name'];

			$curlInit = new Curl;
			$curlInit->spell = $i;
			$curlSession = $curlInit->CurlStart();
			$wowhead = $curlInit->wowhead;

			if (empty($wowhead))
			{
				die ("Error retrieving file");
			}

			//strip tags
			$wowhead = str_ireplace('<a', '', $wowhead);
			$wowhead = str_ireplace('</a>', '', $wowhead);
			$wowhead = strip_tags($wowhead);

			if (strstr($wowhead,'name')==false)//item does not have a name
				{
				echo "Nothing for spell $i<br/>";
			}

			if (strstr($wowhead,'itemset')==true)//item is a set, remove the part after the set name and delete incorrect rows
				{
				$endSet = strrpos($wowhead, 'itemset=');
				$wowhead = substr($wowhead, 0 , $endSet);
				$pdo->delete_rows($pdo->deleteSpellItem,$i);
				
			}

			if (substr_count($wowhead, 'item=')==0) // no items attached to spell
				{
				//check whether the rows exist already
				$pdo->bound_query($pdo->findSpell,array($i));
				$findSpellResult=$pdo->rowcount;

				if ($findSpellResult<1)
				{
					//insert rows
					$pdo->bound_query($pdo->insertSpell,array($i),'None');
				}
			}//end 0 result insert

			//first, if 'item' occurs only once, that is what the recipe teaches
			else if (substr_count($wowhead, 'item=')==1)
				{
					echo "Spell $i teaches one thing <br/>";
					$startPos = stripos($wowhead, 'item=');//find the start of the item id
					$item = substr($wowhead, ($startPos+5), 6);//extract the 6 characters
					$item = preg_replace($pattern,"", $item);//replace any non-numbers

					//update spell name (this is irrespective of the update)
					$data = $api->getRecipeApi()->getRecipe($i);
					$spellName = $data['name'];
					$pdo->bound_query($pdo->updateSpell,array($spellName,$i),'None');

					//check whether the rows exist already and insert if they don't
					$pdo->check_values($i,$item,'product');


				}//end single result insert

			else if (substr_count($wowhead, 'item=')>1)
				{
					echo "more than one reagent found for spell $i<br/>";

					//if it occurs more than once, we must extract the data, remove the string using substr_replace and parse it again
					//extract the item that the recipe makes (last item)
					$startPos = strripos($wowhead, 'item=');//find the start of the last item id
					$item = substr($wowhead, ($startPos+5), 6);//extract the 6 characters
					$item = preg_replace($pattern,"", $item);//replace any non-numbers

					//update spell name (this is irrespective of the update)
					$data = $api->getRecipeApi()->getRecipe($i);
					$spellName = $data['name'];
					$pdo->bound_query($pdo->updateSpell,array($spellName,$i),'None');

					//insert the product information
					//check whether the rows exist already and insert if they don't
					echo $pdo->check_values($i,$item,'product');

					echo "Inserted item $item for spell $i <br/>";

					while (substr_count($wowhead, 'item=')>1)
					{
						//echo "found 1 count<br/>";
						$startPos = stripos($wowhead, 'item=');//find the start of the first item id (i.e. first reagent)
						$item = substr($wowhead, ($startPos+5), 6);//extract the 6 characters
						$item = preg_replace($pattern,'', $item);//replace any non-numbers

						//update spell name (this is irrespective of the update
						$data = $api->getRecipeApi()->getRecipe($i);
						$spellName = $data['name'];
						$pdo->bound_query($pdo->updateSpell,array($spellName,$i),'None');

						//check whether the rows exist already and insert if they don't
						$pdo->check_values($i,$item,'reagent');

						echo "Inserted reagent $item for spell $i <br/>";
						$wowhead = preg_replace($pattern2,'',$wowhead,1);//remove the item reference

					}
					echo "<br/>";

				}//end multi item insert

			flush();
			curl_close($curlInit->ch);
			$i++;

		}//end global try
		catch (exception $e)
		{
			echo $i." ";
			echo 'Caught exception for recipe: ', $e->getMessage()," (Row deleted)<br/>";
			if ($e->getMessage()=='Invalid recipe id.')
			{
			$pdo->delete_rows($pdo->deleteSpellItem,$i);
			$pdo->delete_rows($pdo->deleteSpell,$i);			
			}

			$i++;
		}
	}//end statement loop


	//END RECIPE BLOCK
	//update items with name etc.
	try{
	
	$STH1 = $DBH->query('SELECT item_id from item where name is null');//get all items to be updated
		}
		catch(PDOException $e) {
					echo $e->getMessage();
				}
		
	while($row = $STH1->fetch())
	{

		try{
			$data = $api->getItemsApi()->getItem($row[0]);//send request
		}
		catch(exception $e)
		{echo "error getting item " . $e;}

		try{
			$itemName = $DBH->quote($data['name']);
			$itemQuality = $data['quality'];
			$itemUrl = $data['icon'];
			$itemClass = $data['itemClass'];
			$itemSubClass = $data['itemSubClass'];
			$itemLevel = $data['itemLevel'];
			$itemSkill = $data['requiredSkill'];
			$itemReqLevel = $data['requiredLevel'];
			$itemSkillRank = $data['requiredSkillRank'];
			$itemId = $row[0];

			$data_ar=array($itemName,$itemQuality,$itemUrl,$itemClass,$itemSubClass,$itemLevel,$itemSkill,$itemReqLevel,$itemSkillRank);
			$quotedString = "UPDATE item set name = $itemName, quality = '$itemQuality', url = '$itemUrl', item_class = '$itemClass', item_sub_class = '$itemSubClass', item_level = '$itemLevel', required_skill = '$itemReqSkill', required_level = '$itemReqLevel', required_skill_rank = '$itemSkillRank', datestamp = now(), userstamp=2 WHERE item_id = '$itemId'";

			$STH = $DBH->query($quotedString);
			echo $row[0] . " successfully updated<br/>";

		}
		catch(PDOException $e) {
			echo "Error updating item: " . $e;
		}
	}//end item update
	echo "Done running<br/>";

	$pdo->try_query("select spell_id from spell_item order by datestamp desc limit 0,1",'One');
	$maxSpellEnd = $pdo->result;
	echo "<br/>Highest updated record is now $maxSpellEnd[0]<br/><br/>";




}//end if




?>